/**
 * 单位变更列表状态管理
 * 用于单位变更页面和详情页之间的导航
 */

import { defineStore } from 'pinia'
import { getChangeListApi } from '@/api/athlete/change/index'
import { ChangeType, type ChangeQueryParams } from '@/api/athlete/change/types'
import type { AthleteViewModel } from '@/api/athlete/transformer'

interface OrgChangeListState {
	// 完整的运动员列表数据
	list: AthleteViewModel[]

	// 分页信息
	pagination: {
		currentPage: number
		pageSize: number
		total: number
	}

	// 搜索条件
	queryParams: ChangeQueryParams

	// 当前查看的运动员索引
	currentIndex: number

	// 是否正在加载
	loading: boolean
}

export const useOrgChangeListStore = defineStore('orgChangeList', {
	state: (): OrgChangeListState => ({
		list: [],
		pagination: {
			currentPage: 1,
			pageSize: 10,
			total: 0
		},
		queryParams: {},
		currentIndex: -1,
		loading: false
	}),

	getters: {
		/**
		 * 当前运动员
		 */
		currentAthlete: state => {
			if (state.currentIndex >= 0 && state.currentIndex < state.list.length) {
				return state.list[state.currentIndex]
			}
			return null
		},

		/**
		 * 是否有上一条
		 */
		hasPrev: state => state.currentIndex > 0,

		/**
		 * 是否有下一条
		 */
		hasNext: state => {
			// 如果还在当前页内，直接判断
			if (state.currentIndex < state.list.length - 1) {
				return true
			}
			// 如果是最后一条，判断是否还有下一页
			const totalPages = Math.ceil(state.pagination.total / state.pagination.pageSize)
			return state.pagination.currentPage < totalPages
		},

		/**
		 * 上一条运动员ID
		 */
		prevId: state => {
			if (state.currentIndex > 0) {
				const item = state.list[state.currentIndex - 1]
				return item?.infoId || item?.athleteId
			}
			return null
		},

		/**
		 * 下一条运动员ID
		 */
		nextId: state => {
			if (state.currentIndex < state.list.length - 1) {
				const item = state.list[state.currentIndex + 1]
				return item?.infoId || item?.athleteId
			}
			return null
		},

		/**
		 * 当前在总数据中的位置（用于显示 "第 X / Y 条"）
		 */
		currentPosition: state => {
			// 如果没有设置当前索引，但有数据，返回1（第一条）
			if (state.currentIndex < 0) {
				return state.list.length > 0 ? 1 : 0
			}
			return (state.pagination.currentPage - 1) * state.pagination.pageSize + state.currentIndex + 1
		},

		/**
		 * 是否接近当前页末尾（剩余3条时预加载下一页）
		 */
		shouldPreloadNext: state => {
			return state.currentIndex >= state.list.length - 3
		}
	},

	actions: {
		/**
		 * 加载列表数据
		 */
		async loadList(params?: ChangeQueryParams) {
			try {
				this.loading = true

				// 更新查询参数，确保变更类型为单位变更
				const queryParams = {
					...params,
					changeType: ChangeType.ORG_CHANGE
				}
				this.queryParams = queryParams

				const res = await getChangeListApi({
					pageNum: this.pagination.currentPage,
					pageSize: this.pagination.pageSize,
					...this.queryParams
				})

				// 存储完整的变更数据（不需要转换，直接使用API数据）
				this.list = res.data.rows as AthleteViewModel[]
				this.pagination.total = res.data.total

				return this.list
			} catch (error) {
				console.error('加载单位变更列表失败:', error)
				throw error
			} finally {
				this.loading = false
			}
		},

		/**
		 * 设置当前运动员（从列表进入详情时调用）
		 * 注意：变更数据中 infoId 是运动员ID，id 是变更记录ID
		 */
		setCurrentById(id: string | number) {
			console.log('[单位变更Store] setCurrentById调用', {
				id,
				listLength: this.list.length,
				list: this.list.map(item => ({
					infoId: item.infoId,
					athleteId: item.athleteId
				}))
			})
			const index = this.list.findIndex(item => String(item.infoId || item.athleteId) === String(id))
			if (index >= 0) {
				this.currentIndex = index
				console.log('[单位变更Store] 找到索引:', index)
				return true
			}
			console.warn('[单位变更Store] 未找到ID:', id)
			return false
		},

		/**
		 * 切换到上一条
		 */
		async gotoPrev(): Promise<string | number | null> {
			console.log('[单位变更Store] gotoPrev调用', {
				hasPrev: this.hasPrev,
				currentIndex: this.currentIndex,
				listLength: this.list.length,
				currentPage: this.pagination.currentPage
			})

			if (!this.hasPrev) {
				console.warn('[单位变更Store] 没有上一条了')
				return null
			}

			// 如果在当前页内，直接切换
			if (this.currentIndex > 0) {
				this.currentIndex--
				const result = this.list[this.currentIndex].infoId || this.list[this.currentIndex].athleteId!
				console.log('[单位变更Store] 返回上一条ID:', result)
				return result
			}

			// 需要加载上一页
			if (this.pagination.currentPage > 1) {
				this.pagination.currentPage--
				await this.loadList()
				// 跳到新加载页的最后一条
				this.currentIndex = this.list.length - 1
				const result = this.list[this.currentIndex].infoId || this.list[this.currentIndex].athleteId!
				console.log('[单位变更Store] 加载上一页后返回ID:', result)
				return result
			}

			console.warn('[单位变更Store] gotoPrev返回null')
			return null
		},

		/**
		 * 切换到下一条
		 */
		async gotoNext(): Promise<string | number | null> {
			console.log('[单位变更Store] gotoNext调用', {
				hasNext: this.hasNext,
				currentIndex: this.currentIndex,
				listLength: this.list.length,
				currentPage: this.pagination.currentPage,
				total: this.pagination.total
			})

			if (!this.hasNext) {
				console.warn('[单位变更Store] 没有下一条了')
				return null
			}

			// 如果在当前页内，直接切换
			if (this.currentIndex < this.list.length - 1) {
				this.currentIndex++
				const result = this.list[this.currentIndex].infoId || this.list[this.currentIndex].athleteId!
				console.log('[单位变更Store] 返回下一条ID:', result)
				return result
			}

			// 需要加载下一页
			const totalPages = Math.ceil(this.pagination.total / this.pagination.pageSize)
			if (this.pagination.currentPage < totalPages) {
				this.pagination.currentPage++
				await this.loadList()
				// 跳到新加载页的第一条
				this.currentIndex = 0
				const result = this.list[this.currentIndex].infoId || this.list[this.currentIndex].athleteId!
				console.log('[单位变更Store] 加载下一页后返回ID:', result)
				return result
			}

			console.warn('[单位变更Store] gotoNext返回null')
			return null
		},

		/**
		 * 移除无效数据（当数据被删除时）
		 * 注意：变更数据中 infoId 是运动员ID
		 */
		removeInvalidItem(id: string | number) {
			const index = this.list.findIndex(item => String(item.infoId || item.athleteId) === String(id))
			if (index >= 0) {
				this.list.splice(index, 1)
				// 调整当前索引
				if (this.currentIndex >= index && this.currentIndex > 0) {
					this.currentIndex--
				}
				// 更新总数
				this.pagination.total = Math.max(0, this.pagination.total - 1)
			}
		},

		/**
		 * 重置状态
		 */
		reset() {
			this.list = []
			this.pagination = {
				currentPage: 1,
				pageSize: 10,
				total: 0
			}
			this.queryParams = {}
			this.currentIndex = -1
			this.loading = false
		},

		/**
		 * 更新分页大小
		 */
		setPageSize(pageSize: number) {
			this.pagination.pageSize = pageSize
			this.pagination.currentPage = 1
		},

		/**
		 * 更新当前页
		 */
		setCurrentPage(page: number) {
			this.pagination.currentPage = page
		}
	}
})
